#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

LN* BuyNewNode(int val)
{
	LN* newnode = (LN*)malloc(sizeof(LN));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	newnode->data = val;
	newnode->prev = newnode->next = NULL;

	return newnode;
}

LN* ListInit()
{
	LN* phead = BuyNewNode(-1);

	if (phead == NULL)
	{
		printf("malloc fail\n");
		return NULL;
	}

	phead->prev = phead;
	phead->next = phead;

	return phead;
}

void ListPrint(LN* phead)
{
	assert(phead);
	assert(!ListEmpty(phead));

	LN* cur = phead->next;

	printf("guard->");
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool ListEmpty(LN* phead)
{
	assert(phead);

	return phead->next == phead;
}

void ListPushBack(LN* phead, LDT val)
{
	assert(phead);

	LN* newnode = BuyNewNode(val);
	LN* ptail = phead->prev;

	ptail->next = newnode;
	newnode->prev = ptail;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListPushFront(LN* phead, LDT val)
{
	assert(phead);

	LN* newnode = BuyNewNode(val);
	LN* pnext = phead->next;

	newnode->prev = phead;
	newnode->next = pnext;
	phead->next = newnode;
	pnext->prev = newnode;
}

void ListPopFront(LN* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListErase(phead->next);

}

void ListPopBack(LN* phead)
{
	assert(phead);
	assert(phead->next != phead);

	ListErase(phead->prev);
}

LN* ListFind(LN* phead, LDT val)
{
	assert(phead);

	LN* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == val)
		{
			return cur;
		}
		cur = cur->next;
	}

	return NULL;
}

void ListInsert(LN* pos, LDT val)
{
	assert(pos);

	LN* newnode = BuyNewNode(val);
	LN* pnext = pos->next;

	newnode->next = pnext;
	newnode->prev = pos;
	pos->next = newnode;
	pnext->prev = newnode;
}

void ListErase(LN* pos)
{
	assert(pos);
	assert(pos->next != pos);

	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}

void ListDestroy(LN* phead)
{
	assert(phead);

	LN* cur = phead->next;

	while (cur != phead)
	{
		LN* curnext = cur->next;
		free(cur);
		cur = curnext;
	}

	free(phead);
}